import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { queryParkinglotNames } from '@/pages/Parking/Spot/service';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Tooltip } from 'antd';
import { useModel } from 'umi';
import { mapVehicleType } from '../utils';
import CreateMemberCard from './components/CreateMemberCard';
import UpdataMemberCard from './components/UpdataMemberCard';
import { queryMemberCards, removeMemberCard } from './service';
import type { MemberCardTableItem } from './types.d';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.member || []) : new Set();
  const ifDelete = auths.has(Auths.DELETE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifCreate = auths.has(Auths.CREATE);
  const columns: ProColumns<MemberCardTableItem>[] = [
    {
      title: '模板卡名',
      dataIndex: 'cardName',
      align: 'center',
      hideInForm: true,
    },
    {
      title: '模板卡号',
      dataIndex: 'cardNo',
      align: 'center',
      // hideInTable: true,
      copyable: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '适用车型',
      dataIndex: 'vehicleType',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) =>
        record?.vehicleType?.map((item) => mapVehicleType(item)).join(';') || '-',
    },
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      align: 'center',
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      render: (_, record) => record?.ownerInfo?.ownerName,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
    },
    {
      title: '路段名称',
      align: 'center',
      dataIndex: 'parkingLots',
      hideInForm: true,
      fieldProps: { showSearch: true },
      render: (_, record) => {
        let tempText = '-';
        if (record.allParkValid) {
          tempText = '全路段通用';
        } else {
          tempText =
            record?.parkingLots?.map((item) => item.parkingLotName).join('; ') ||
            record.parkingLotName;
        }

        return (
          <Tooltip title={tempText}>
            <div
              style={{
                maxWidth: '300px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                margin: '0 auto',
              }}
            >
              {tempText}
            </div>
          </Tooltip>
        );
      },
      debounceTime: 300,
      request: (val) => queryParkinglotNames(val.keyWords),
    },
    {
      title: '类型/价格',
      align: 'center',
      dataIndex: 'typeInfo',
      hideInForm: true,
      hideInSearch: true,
      // renderText: (text) => text / 100,
      render: (_, record) => {
        if (!record.typeInfo) return '-';
        const typeInfo = record.typeInfo;
        return (
          <div>
            {typeInfo['month'] && <div>{typeInfo['month'].price / 100}元/ 30天</div>}
            {typeInfo['season'] && <div>{typeInfo['season'].price / 100}元/ 90天</div>}
            {typeInfo['year'] && <div>{typeInfo['year'].price / 100}元/ 365天</div>}
          </div>
        );
      },
    },
    // {
    //   title: '类型',
    //   align: 'center',
    //   dataIndex: 'type',
    //   hideInForm: true,
    //   valueEnum: {
    //     year: '年卡',
    //     season: '季卡',
    //     month: '月卡',
    //   },
    // },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      hideInForm: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '最后修改时间',
      align: 'center',
      dataIndex: 'lastModifyTime',
      hideInForm: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      valueType: 'option',
      render: (t, record, x, action) =>
        ifModify || ifDelete
          ? [
              ifModify && <UpdataMemberCard reload={() => action?.reload()} memberCard={record} />,
              ifDelete && (
                <ConfirmModal
                  reload={() => action?.reload()}
                  operFunc={async () => await removeMemberCard(record.cardNo)}
                  text={`是否确定删除会员卡「${record.cardNo}」`}
                />
              ),
            ]
          : [<PlaceHolderCpn key={record._id} />],
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '模板卡',
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            { path: '/member', breadcrumbName: '会员卡管理' },
            { path: '/member/cards', breadcrumbName: '模板卡' },
          ],
        },
      }}
    >
      <ProTable<MemberCardTableItem>
        columns={columns}
        rowKey="cardNo"
        scroll={{ x: true }}
        search={{
          labelWidth: 'auto',
        }}
        style={{ whiteSpace: 'nowrap' }}
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryMemberCards(param, sort);
          return res;
        }}
        toolBarRender={(action) => [
          ifCreate && <CreateMemberCard reload={() => action?.reload()} />,
        ]}
      />
    </PageHeaderWrapper>
  );
};
